package cn.initcap.rabbitmq;

import cn.initcap.entity.SeckillOrder;
import cn.initcap.entity.SeckillUser;
import cn.initcap.redis.RedisService;
import cn.initcap.service.GoodsService;
import cn.initcap.service.OrderService;
import cn.initcap.service.SeckillService;
import cn.initcap.vo.GoodsVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author initcap
 * @date 2018/8/10 PM5:55
 */
@Slf4j
@Service
public class MqReceiver {

    private final GoodsService goodsService;
    private final OrderService orderService;
    private final SeckillService seckillService;

    @Autowired
    public MqReceiver(GoodsService goodsService, OrderService orderService, SeckillService seckillService) {
        this.goodsService = goodsService;
        this.orderService = orderService;
        this.seckillService = seckillService;
    }

    @RabbitListener(queues = MqConfig.MIAOSHA_QUEUE)
    public void receive(String message) {
        log.info("receive message:" + message);
        SeckillMessage mm = RedisService.stringToBean(message, SeckillMessage.class);
        SeckillUser user = mm.getUser();
        long goodsId = mm.getGoodsId();

        GoodsVo goods = goodsService.getGoodsVoByGoodsId(goodsId);
        int stock = goods.getStockCount();
        if (stock <= 0) {
            return;
        }
        //判断是否已经秒杀到了
        SeckillOrder order = orderService.getMiaoshaOrderByUserIdGoodsId(user.getId(), goodsId);
        if (order != null) {
            return;
        }
        //减库存 下订单 写入秒杀订单
        seckillService.miaosha(user, goods);
    }

    @RabbitListener(queues = MqConfig.QUEUE)
    public void receive2(String message) {
        log.info("receive message:" + message);
    }

    @RabbitListener(queues = MqConfig.TOPIC_QUEUE1)
    public void receiveTopic1(String message) {
        log.info(" topic  queue1 message:" + message);
    }

    @RabbitListener(queues = MqConfig.TOPIC_QUEUE2)
    public void receiveTopic2(String message) {
        log.info(" topic  queue2 message:" + message);
    }

    @RabbitListener(queues = MqConfig.HEADER_QUEUE)
    public void receiveHeaderQueue(byte[] message) {
        log.info(" header  queue message:" + new String(message));
    }

}
